package edu.hawaii.ics414;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

/**
 * The Ajax class for retrieving data
 * 
 * @author Matthew Mizumoto
 * 
 */
public class Ajax {

  /*
   * Builds a URL string containing form information and returns the value that is returned from the
   * script.
   */
  public static String send(String url, Map<String, String> params) {
    try {
      URLConnection conn = new URL(url).openConnection();
      conn.setDoOutput(true);

      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
      StringBuilder sb = new StringBuilder();
      for (Map.Entry<String, String> entry : params.entrySet()) {
        sb.append(entry.getKey() + "=").append(URLEncoder.encode(entry.getValue(), "UTF-8"))
            .append("&");
      }
      wr.write(sb.toString());
      wr.flush();
      wr.close();

      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String response = rd.readLine();
      rd.close();
      return response;
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}
